package com.instagram.instadownloader.utils.download;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.net.URL;
import java.net.URLConnection;

import org.apache.commons.io.FilenameUtils;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;

import com.instagram.instadownloader.InstaDownloaderApp;
import com.instagram.instadownloader.MainActivity;
import com.vine.vinedownloader.R;

public class DownloadTask extends AsyncTask<String, Integer, Integer>{
	
	private final int			NOTIFI_ID = 1122;
	private static final int STATUS_DOWNLOAD_SUCCESS = 2;
	private static final int STATUS_DOWNLOAD_FAIL = 3;
	
	private PendingIntent 		contentIntent;
	
	private DownloadData		mDownloadData;
	
	private HandlerDownload		mHandlerDownload;
	
	private Context				mContext;
	
	private NotificationManager mNotificationManager;
	
	private Notification		notification;
	
	private NotificationCompat.Builder mBuilder;
	
	public DownloadTask(String url,String absolutePath,OnDownloadListener listener) {
		mContext = InstaDownloaderApp.getAppContext();
		mDownloadData = new DownloadData();
		mDownloadData.url = url;
		mDownloadData.absolutePath = absolutePath;
		mDownloadData.downloadListener = listener;
	}
	
	public DownloadTask(String url,String absolutePath,OnDownloadListener listener,HandlerDownload handler){
		this(url,absolutePath,listener);
		mHandlerDownload = handler;
	}
	
	@Override
	protected void onPreExecute() {
		
		/*
		 * show notification info status download
		 * */
		mDownloadData.downloadListener.onDownloadPrepare();
		initNotification();
		super.onPreExecute();
	}
	
	
	@Override
	protected Integer doInBackground(String... params) {
		File fileOut = new File(mDownloadData.absolutePath);
		if(fileOut.exists())
			fileOut.mkdirs();
		try {
			//create Url
			URL url = new URL(mDownloadData.url);
			
			//create Connection to Data
			URLConnection connection = url.openConnection();
			connection.setReadTimeout(5000);
			connection.setConnectTimeout(5000);
//			connection.connect();
			
			// getting file length
            int lenghtOfFile = connection.getContentLength();
			
	        FileOutputStream output = new FileOutputStream(fileOut);
	        
	        BufferedInputStream input = new BufferedInputStream(connection.getInputStream());

	        //create buffer contain content that input read
	        byte[] buffer = new byte[1024];
	        
	        //now begin to read and write data
	        long total=0;
	        int count;
	        
	        //read into byte array
	        while((count = input.read(buffer))!=-1){
	        	if(mHandlerDownload!=null && !mHandlerDownload.getDownloadAble())
	        		break;
	        	total +=count;	
	        	publishProgress((int)((total*100)/lenghtOfFile));
	        	output.write(buffer, 0, count); 
	        }
	        
	        output.flush();
	        output.close();
	        input.close(); 
	        if(mHandlerDownload!=null && !mHandlerDownload.getDownloadAble()){
	        	if(fileOut.exists())
					fileOut.delete();
				return STATUS_DOWNLOAD_FAIL;
	        }
        	return STATUS_DOWNLOAD_SUCCESS;
		} catch (Exception e) {
			e.printStackTrace();
			if(fileOut.exists())
				fileOut.delete();
			return STATUS_DOWNLOAD_FAIL;
		}
	}

	
	@Override
	protected void onProgressUpdate(Integer... values) {
		
		mDownloadData.downloadListener.onProcessUpdate(values[0]);
	}
	
	
	@Override
	protected void onPostExecute(Integer result) {
		switch(result) {
			case STATUS_DOWNLOAD_SUCCESS:
				{
					mDownloadData.downloadListener.onDownloadSucess(mDownloadData.absolutePath);
	        		
	        		//update notifi
	        		notification.setLatestEventInfo(mContext, "download completed.", FilenameUtils.getName(mDownloadData.absolutePath), contentIntent);
	        		notification.flags = Notification.FLAG_AUTO_CANCEL;
	        		mNotificationManager.notify(NOTIFI_ID, notification);

				}
				break;
			case STATUS_DOWNLOAD_FAIL:
				{
					mDownloadData.downloadListener.onDownloadFail(null);
		    		
		    		//update notifi
	        		notification.setLatestEventInfo(mContext, "download failed.", FilenameUtils.getName(mDownloadData.absolutePath), contentIntent);
	        		notification.flags = Notification.FLAG_AUTO_CANCEL;
	        		mNotificationManager.notify(NOTIFI_ID, notification);
		    
				}
				break;
				default:
					break;
		}
	}

	
	private void initNotification() {
		mNotificationManager =
			    (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
		
		notification = new Notification(R.drawable.ic_instadownloader, mContext.getResources().getString(
											R.string.app_name),System.currentTimeMillis());
		
		Intent notifyIntent = new Intent(mContext, MainActivity.class);
		notifyIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		contentIntent = PendingIntent.getActivity(mContext, 0,new Intent(), 0);
		  
		notification.setLatestEventInfo(mContext,"Downloading...",FilenameUtils.getName(mDownloadData.absolutePath), contentIntent);

		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		mNotificationManager.notify(NOTIFI_ID,notification);
	}
	
	private class DownloadData{
		public String url;
		public String absolutePath;
		public OnDownloadListener downloadListener;
	}
	
	public interface OnDownloadListener{
		public void onDownloadPrepare();
		public void onProcessUpdate(int process);
		public void onDownloadSucess(String absolutePath);
		public void onDownloadFail(String fail);
	}
	
}
